// 星云类（背景装饰 + 移动效果）
import { TimeManager } from './TimeManager.js';

export class Nebula {
    constructor(x, y, size, moveSpeed) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.opacity = Math.random() * 0.3 + 0.1;
        this.color = this.getNebulaColor();
        this.pulsePhase = Math.random() * Math.PI * 2;
        this.pulseSpeed = 0.12; // 0.002 * 60 = 0.12弧度/秒
        this.moveSpeed = moveSpeed * 60; // 转换为像素/秒
    }
    
    getNebulaColor() {
        const colors = [
            '#ff6b6b', '#4ecdc4', '#45b7d1', 
            '#96ceb4', '#ffeaa7', '#fd79a8'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
    }
    
    update(deltaTime) {
        // 脉冲效果（基于时间）
        this.pulsePhase = TimeManager.updatePhase(this.pulsePhase, deltaTime, this.pulseSpeed);
        this.opacity = 0.1 + Math.sin(this.pulsePhase) * 0.2;
        
        // 移动效果（向下移动，模拟飞行前进）
        this.y += this.moveSpeed * (deltaTime / 1000);
        
        // 当星云移出屏幕底部时，重新在顶部出现
        if (this.y > 800 + this.size) {
            this.y = -this.size;
            this.x = Math.random() * 1200;
        }
    }
    
    render(ctx) {
        ctx.save();
        
        const gradient = ctx.createRadialGradient(
            this.x, this.y, 0,
            this.x, this.y, this.size
        );
        
        // 使用RGBA格式
        const baseColor = this.hexToRgb(this.color);
        
        gradient.addColorStop(0, `rgba(${baseColor.r}, ${baseColor.g}, ${baseColor.b}, ${this.opacity})`);
        gradient.addColorStop(0.5, `rgba(${baseColor.r}, ${baseColor.g}, ${baseColor.b}, ${this.opacity * 0.5})`);
        gradient.addColorStop(1, `rgba(${baseColor.r}, ${baseColor.g}, ${baseColor.b}, 0)`);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.restore();
    }
    
    hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : {r: 255, g: 255, b: 255};
    }
}